﻿using UnityEngine;
using System.Collections.Generic;
using System.Collections;

/// <summary>
/// 资源管理，加载和卸载，路径分为Resources（prefab）和Application.persistentDataPath（assetbundle）
/// </summary>
public class ResMgr : MonoBehaviour
{
    public static ResMgr Instance;
    /// <summary>
    /// 资源加载模式
    /// </summary>
    public static RESMODE mode = RESMODE.RES;

    public static Dictionary<string, AssetBundle> abs = new Dictionary<string, AssetBundle>();

    /// <summary>
    /// 预制体路径Root
    /// </summary>
    public static string resPathRoot = "";

    private void Awake()
    {
        Instance = this;
    }
    /// <summary>
    /// 加载
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public GameObject Load(string name)
    {
        GameObject obj = null;
        if (mode == RESMODE.RES)
        {
            obj = Resources.Load<GameObject>(resPathRoot + "/" + name);
        }

        if (mode == RESMODE.AB)
        {
            name = name.ToLower();
            Debug.LogWarning("加载AB");

            if (abs.ContainsKey(name))
            {
                if (abs[name] != null)
                {
                    abs[name].Unload(true);
                }
                abs.Remove(name);
            }

            AssetBundle ab = AssetBundle.LoadFromFile(Application.persistentDataPath + "/AB/" + name + ".t");
            obj = ab.LoadAsset<GameObject>(name);

            abs.Add(name, ab);
            //ab.Unload(false);
            Debug.LogWarning("卸载AB");
            ab = null;
        }

        return obj;
    }


    public void Unload(string name, bool state)
    {
        if (abs.ContainsKey(name))
        {
            abs[name].Unload(state);
        }
    }

}

/// <summary>
/// 资源加载模式
/// </summary>
public enum RESMODE
{
    /// <summary>
    /// 只作为开发测试用Resource
    /// </summary>
    RES,
    /// <summary>
    /// 发布用Assetbundle
    /// </summary>
    AB
}
